﻿using EaseDapper.Interface;
using System.Collections.Concurrent;

namespace EaseDapper.Providers.ExpressionBuilderProvider
{
    public class BuilderProvider
    {
        //private static BuilderProvider _builder;
        //private static readonly object obj_builder_lock = new object();
        private static ConcurrentDictionary<string, IAbstractFactory> queryFactorys;

        internal BuilderProvider()
        {
            queryFactorys = new ConcurrentDictionary<string, IAbstractFactory>();
        }

        internal BuilderProvider(ConnectConfig config)
        {
            GlobalDatas.Config = config;
            queryFactorys = new ConcurrentDictionary<string, IAbstractFactory>();
        }


        public IQueryExpressions<T> QueryBuilder<T>() where T : class
        {
            IAbstractFactory abstractFactory = GetBuilderFactory();
            return abstractFactory.CreatQuery<T>();
        }

        public IUpdateExpressions<T> UpdateBuilder<T>() where T : class
        {
            IAbstractFactory abstractFactory = GetBuilderFactory();
            return abstractFactory.CreatUpdate<T>();
        }

        public IDeleteExpressions<T> DeleteBuilder<T>() where T : class
        {
            IAbstractFactory abstractFactory = GetBuilderFactory();
            return abstractFactory.CreatDelete<T>();
        }

        internal IAbstractFactory GetBuilderFactory()
        {
            IAbstractFactory abstractFactory;
            if (queryFactorys.TryGetValue(GlobalDatas.Config.DbType, out IAbstractFactory query))
            {
                abstractFactory = query;
            }
            else
            {
                abstractFactory = InstanceFactory.GetAbstractFactory();
                queryFactorys.TryAdd(GlobalDatas.Config.DbType, abstractFactory);
            }
            return abstractFactory;
        }
    }
}
